﻿/*
The database must have a MEMORY_OPTIMIZED_DATA filegroup
before the memory optimized object can be created.
*/

create procedure [mem].[kvDelete]
(
	@Key varchar(255) not null,
	@Version int not null
)
with NATIVE_COMPILATION, SCHEMABINDING, EXECUTE AS OWNER 
as begin atomic with(TRANSACTION ISOLATION LEVEL = SNAPSHOT, LANGUAGE = 'English')

	declare @todelete mem.kvVersions
	insert @todelete select KeyId, [Version] from mem.kv where [Key] = @Key
	
	if @@rowcount = 0 return;
	
	declare @KeyId bigint
	declare @DeletedVersion binary(8)
	select @KeyId = KeyId, @DeletedVersion = [Version] from @todelete
	 
	if @Version != @DeletedVersion
		begin
			declare @message nvarchar(350)
			set @message = 'Concurrency violation for key [' + @Key + ']. Reselect the value and try again.';
			throw 60001, @message, 1;
		end

	delete mem.kv where [Key] = @Key
	delete from mem.kvValues where [KeyId] = @KeyId
end
